using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Wicresoft.RDW.Helper;
using Wicresoft.RDW.Model;
using Wicresoft.RDW.Presentation;
using Wicresoft.RDW.Utility;
using System.Threading;
using System.Globalization;

namespace Wicresoft.RDW.Ajax
{
    /// <summary>
    /// Summary description for Service
    /// </summary>
    public class Service : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }
        protected HttpRequest Request
        {
            get
            {
                return HttpContext.Current.Request;
            }
        }
        protected HttpResponse Response
        {
            get
            {
                return HttpContext.Current.Response;
            }
        }
        protected string Category
        {
            get
            {
                return Request.QueryString["category"];
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            if (Category.Equals("GetVisitRequest", StringComparison.OrdinalIgnoreCase))
            {
                ExecGetVisitRequest();
                return;
            }
            if (Category.Equals("GetLabList", StringComparison.OrdinalIgnoreCase))
            {
                ExecGetLabList();
                return;
            }
            if (Category.Equals("GetUserName", StringComparison.OrdinalIgnoreCase))
            {
                Response.Write(GetUserName());
                return;
            }
            if (Category.Equals("GetUserByName", StringComparison.OrdinalIgnoreCase))
            {
                Response.Write(GetUserByName());
                return;
            }
            if (Category.Equals("GetVisitType", StringComparison.OrdinalIgnoreCase))
            {
                Response.Write(GetVisitType());
                return;
            }

            Response.Write(string.Empty);
        }

        #region visit request
        private void ExecGetVisitRequest()
        {
            string LabID = Request.Params["LabID"];
            string Year = Request.Params["Year"];
            string Month = Request.Params["Month"];
            if (!string.IsNullOrEmpty(LabID) && !string.IsNullOrEmpty(Year) && !string.IsNullOrEmpty(Month))
            {
                GetInitialDataForCalendar(int.Parse(LabID), int.Parse(Year), int.Parse(Month), Request.Params["Language"]);
            }
        }

        private void GetInitialDataForCalendar(int labID, int year, int month, string Language)
        {

            List<Wicresoft.RDW.Model.Request> VisistRequestsInMonth = default(List<Wicresoft.RDW.Model.Request>);
            List<LabCloseSchedule> closeScheduleList = default(List<LabCloseSchedule>);

            VisistRequestsInMonth = RequestPresent.GetList(x => x.LabId == labID && x.RequestDate.Year == year && x.RequestDate.Month == month && x.Status != 0);
            List<CalendarModel> RequestsInDayOfMonth = new List<CalendarModel>();

            for (int i = 1; i <= DateTime.DaysInMonth(year, month); i++)
            {
                var RequestsInDay = from RequestsByDay in VisistRequestsInMonth
                                    where RequestsByDay.RequestDate.Day == i
                                    select RequestsByDay;
                if (RequestsInDay.Count() != 0)
                {
                    var calendarModel = new CalendarModel();
                    calendarModel.Date = i;
                    List<RequestItem> requestItems = new List<RequestItem>();
                    foreach (var requestItem in RequestsInDay)
                    {
                        var item = new RequestItem();
                        item.Time = string.Format("{0:HH:mm}", Convert.ToDateTime(requestItem.StartTime.ToString()))
                            + "--" + string.Format("{0:HH:mm}", Convert.ToDateTime(requestItem.EndTime.ToString()));
                        item.Status = this.GetStatus(requestItem.Status);
                        item.LinkURL = "/Request/Apply.aspx?pageStatus=Readonly&read=true&id=" + requestItem.RequestId;
                        item.RequestUserDetail = this.GetRequestDetail(requestItem.RequestId, Language);
                        requestItems.Add(item);
                    }
                    calendarModel.Orders = requestItems;
                    RequestsInDayOfMonth.Add(calendarModel);

                }
                else
                {

                    if (closeScheduleList == null)
                    {
                        closeScheduleList = LabCloseSchedulePresent.GetList();
                    }
                    if (closeScheduleList == null) continue;

                    DateTime now = new DateTime(year, month, i);
                    foreach (var closeSchedule in closeScheduleList)
                    {

                        if (now >= closeSchedule.StartDate && now <= closeSchedule.EndDate && closeSchedule.LabId == labID)
                        {
                            var calendarModel = new CalendarModel();
                            calendarModel.Date = i;
                            calendarModel.LabStatus = GetStatus(0);
                            if (closeSchedule.ReasonId > 0)
                            {
                                var reason = ReasonPresent.GetById(closeSchedule.ReasonId);

                                calendarModel.CloseReason = Resources.NameResource.LabCloseSchedule_Reason + ":";

                                if (Utility.Language.EN.ToString() == Language)
                                {
                                    if (reason != null)
                                    {
                                        calendarModel.CloseReason += reason.Desc_EN;
                                    }
                                }
                                else
                                {
                                    if (reason != null)
                                    {
                                        calendarModel.CloseReason += reason.Desc_CN;
                                    }
                                }
                            }
                            else
                            {
                                calendarModel.CloseReason += closeSchedule.OtherReason;
                            }
                            RequestsInDayOfMonth.Add(calendarModel);
                        }
                    }
                }
            }
            Response.Write(JsonConvert.SerializeObject(RequestsInDayOfMonth));

        }

        private string GetStatus(int status)
        {
            if (status == 0)
            {
                return LabStatus.Closed.ToString();
            }
            return ((RequestStatus)status).ToString();
        }

        private string GetUserName()
        {
            var users = from U in UserPresent.GetList()
                        select new
                        {
                            Account = U.Account.Trim()
                        };
            JArray array = new JArray();
            foreach (var item in users)
            {
                array.Add(item.Account.Trim());
            }
            return array.ToString();

        }
        private string GetUserByName()
        {
            string userName = Request.QueryString["name"];
            if (string.IsNullOrEmpty(userName))
                return "";
            var user = UserPresent.GetByCondition(p => p.Account == userName);
            if (user == null)
                return null;

            var returnUser = new
            {
                Id = user.UserId,
                Account = user.Account.Trim(),
                Name = Request.Params["Language"] != "EN" ? user.NameCN : user.NameEN,
                Email = user.Email == null ? "" : user.Email.Trim(),
                Mobile = user.Mobile == null ? "" : user.Mobile.Trim(),
                OfficePhone = user.OfficePhone == null ? "" : user.OfficePhone.Trim(),
                Department = user.BD
            };

            return JsonConvert.SerializeObject(returnUser);
        }

        private string GetVisitType()
        {
            string id = Request.QueryString["id"];
            if (string.IsNullOrEmpty(id))
                return "";
            var visitType = VisitTypePresent.GetById(Convert.ToInt32(id));

            return visitType.ParentId.ToString();
        }

        private RequestDetail GetRequestDetail(int RequestId, string Language)
        {
            if (Language == "EN")
            {
                Thread.CurrentThread.CurrentCulture =
            CultureInfo.CreateSpecificCulture("en-US");
                Thread.CurrentThread.CurrentUICulture =
                   new CultureInfo("en-US");
            }
            else
            {
                Thread.CurrentThread.CurrentCulture =
            CultureInfo.CreateSpecificCulture("zh-CN");
                Thread.CurrentThread.CurrentUICulture =
                   new CultureInfo("zh-CN");
            }
            var requestItem = RequestPresent.GetById(RequestId);

            if (requestItem == null) return null;
            var requestDetail = default(RequestDetail);
            if ((RequestType)requestItem.RequestType == RequestType.Visit)
            {
                requestDetail = this.GetRequestDetailByType(requestItem.RequestUserId, RequestType.Visit, Language);
                var VisitRequest = VisitRequestPresent.GetByCondition(x => x.RequestId == requestItem.RequestId);
                if (VisitRequest != null)
                {
                    requestDetail.CompanyName = Resources.NameResource.Request_CompanyName + ":" + VisitRequest.CompanyName;
                }
            }
            if ((RequestType)requestItem.RequestType == RequestType.Testing)
            {
                requestDetail = this.GetRequestDetailByType(requestItem.RequestUserId, RequestType.Testing, Language);
            }
            if ((RequestType)requestItem.RequestType == RequestType.SiteBorrow)
            {
                requestDetail = this.GetRequestDetailByType(requestItem.RequestUserId, RequestType.SiteBorrow, Language);
            }
            requestDetail.RequestType = Resources.NameResource.Visit_VisitType + ":" + requestDetail.RequestType;
            requestDetail.Telephone = Resources.NameResource.User_Telephone + ":" + requestDetail.Telephone;
            requestDetail.UserName = Resources.NameResource.Request_RequestUserID + ":" + requestDetail.UserName;
            requestDetail.Dept = Resources.NameResource.RequestUserDepartment + ":" + requestDetail.Dept;
            return requestDetail;
        }

        private RequestDetail GetRequestDetailByType(int RequestUserId, RequestType requestType, string Language)
        {
            var requestDetail = new RequestDetail();
            var requestUser = UserPresent.GetById(RequestUserId);

            requestDetail.RequestType = EnumDataSource<RequestType>.GetDisplayValue((int)requestType, Language == "EN" ? "en-US" : "zh-CN");
            if (requestUser != null)
            {
                if (Language != Utility.Language.CN.ToString())
                {
                    requestDetail.UserName = requestUser.NameEN;
                }
                else
                {
                    requestDetail.UserName = requestUser.NameCN;
                }

                requestDetail.Dept = requestUser.BD;
                if (string.IsNullOrEmpty(requestUser.BD))
                {
                    requestDetail.Dept = "--";
                }
                requestDetail.Telephone = requestUser.OfficePhone;
            }
            return requestDetail;
        }
        #endregion

        #region getlablist
        private void ExecGetLabList()
        {
            int locationId = int.Parse(Request.Params["LocationId"]);
            var labs = LabPresent.GetList(x => x.LocationId == locationId).Select(p => new { p.LabId, p.Name }).ToList();
            Response.Write(JsonConvert.SerializeObject(labs));
        }
        #endregion
    }
}
